package drp.snowbell.io;

import java.io.File;
import java.util.List;


import com.google.appengine.api.datastore.Blob;

import drp.snowbell.annotation.AEntity;
import drp.snowbell.annotation.AProperty;
import drp.snowbell.cfg.Config;
import drp.snowbell.entity.Entity;
import drp.snowbell.part.SolidTree;

/**
 * 资源实体类.目前只能存文本数据
 * 
 * @author jimmy
 * 
 */
@AEntity(name = Resource.ENTITY_NAME, parts = "{module:'" + Config.CORE_MODULE_NAME + "'name:'" + SolidTree.SKILL_NAME + "',parameter:'path'}")
public class Resource extends Entity {

	public final static String ENTITY_NAME = "Resource";

	/**
	 * 是否含有子资源
	 */
	@AProperty
	private Boolean isDirectory;

	/**
	 * 资源内容.目前只能存文本数据
	 */
	@AProperty
	private Blob data;

	@AProperty
	private String path;

	@SuppressWarnings("unchecked")
	public List<Resource> getSubResource() {
		if (getIsDirectory()) {
			SolidTree tree = (SolidTree) getPart(SolidTree.SKILL_NAME);
			return (List<Resource>) tree.getChildren();
		} else {
			return null;
		}
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public void setIsDirectory(Boolean isDirectory) {
		this.isDirectory = isDirectory;
	}

	public Boolean getIsDirectory() {
		return isDirectory;
	}

	/**
	 * 把路径转为layer格式
	 * 
	 * @param path
	 *            必须为目录的路径
	 * @return
	 */
	public static String pathToLayer(String path) {
		String ret = null;

		if (path != null) {
			if (File.separatorChar != SolidTree.LEVEL_SEPARATOR_CHAR) {
				ret = path.replace(File.separatorChar, SolidTree.LEVEL_SEPARATOR_CHAR);
			} else {
				ret = path;
			}
			if (ret.charAt(0) != SolidTree.LEVEL_SEPARATOR_CHAR) {
				// 判断开头是否为LEVEL_SEPARATOR_CHAR
				ret = SolidTree.LEVEL_SEPARATOR_CHAR + ret;
			}
			if (ret.charAt(ret.length() - 1) != SolidTree.LEVEL_SEPARATOR_CHAR) {
				// 判断结束是否为LEVEL_SEPARATOR_CHAR
				ret = ret + SolidTree.LEVEL_SEPARATOR_CHAR;
			}
		} else {
			ret = String.valueOf(SolidTree.LEVEL_SEPARATOR_CHAR);
		}
		return ret;
	}

	public Blob getData() {
		return data;
	}

	public void setData(Blob data) {
		this.data = data;
	}
}
